package com.qf.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author jiangjingbo
 * @version V1.0
 * @Project java2203
 * @Package com.qf.filter
 * @Description:
 * @Date 2022/7/7 17:46
 */

/**
 * 该方法属于
 * 自定义网关过滤器1
 */
@Component
public class Filter1 implements GlobalFilter, Ordered {

    /**
     *请求进来会执行这些过滤器的代码 执行后 请求才会被网关分配发请求
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("============自定义过滤器1");
        //1.获取请求中的token 令牌
            //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
            //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //获取请求的头中的token对象
        String token = request.getHeaders().getFirst("token");

        //2. 判断如果获取不到token就认为是没有权限访问, 抛出401异常
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 返回的数字，就是如果有多个过滤器 他们执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
